<?php
/**
 * 自定义函数
 *
 * @author 点沐
 * @url 
 */

function show_json($status = 1, $return = NULL){
	$ret = array('status' => $status, 'result' => ($status == 1 ? array('url' => referer()) : array()));
	if (!(is_array($return))) 
	{
		if ($return) 
		{
			$ret['result']['message'] = $return;
		}
		exit(json_encode($ret));
	}
	else 
	{
		$ret['result'] = $return;
	}
	if (isset($return['url'])) 
	{
		$ret['result']['url'] = $return['url'];
	}
	else if ($status == 1) 
	{
		$ret['result']['url'] = referer();
	}
	exit(json_encode($ret));
}
if (!function_exists('m')) {
	function m($name = '')
	{
		static $_modules = array();

		if (isset($_modules[$name])) {
			return $_modules[$name];
		}

		$model = IMFOX_ROOT_CORE . 'model/' . strtolower($name) . '.php';

		if (!is_file($model)) {
			exit(' Model ' . $name . ' Not Found!');
		}

		require_once $model;
		$class_name = ucfirst($name) . '_ImfoxEosModel';
		$_modules[$name] = new $class_name();
		return $_modules[$name];
	}
}
if( !function_exists("com") ) 
{
	function com($name = "") 
	{
		static $_coms = array( );
		if( isset($_coms[$name]) ) 
		{
			return $_coms[$name];
		}
		
		$model = IMFOX_ROOT_CORE . "com/" . strtolower($name) . ".php";
		if( !is_file($model) ) 
		{
			return false;
		}
		require_once(IMFOX_ROOT_CORE . "inc/com_model.php");
		require_once($model);
		$class_name = ucfirst($name) . "_ImfoxEosComModel";
		$_coms[$name] = new $class_name($name);
		return $_coms[$name];
		// if( com_perm_check_com($name) ) 
		// {
		// 	return $_coms[$name];
		// }
		// $_coms[$name] = false;
		// return $_coms[$name];
	}
}
if( !function_exists("com_run") ) 
{
	function com_run($name = "") 
	{
		$names = explode("::", $name);
		$com = com($names[0]);
		if( !$com ) 
		{
			return false;
		}
		if( !method_exists($com, $names[1]) ) 
		{
			return false;
		}
		$func_args = func_get_args();
		$args = array_splice($func_args, 1);
		return call_user_func_array(array( $com, $names[1] ), $args);
	}
}
if( !function_exists("slog") ) 
{
	function slog($type = "", $op = "") 
	{
		com_run("log::skuLog", $type, $op);
	}
}
if( !function_exists("save_media") ) 
{
	function save_media($url, $enforceQiniu = false) 
	{
		global $_W;
		setting_load("remote");
		if( !empty($_W["setting"]["remote"]["type"]) ) 
		{
			if( $_W["setting"]["remote"]["type"] == ATTACH_FTP ) 
			{
				$_W["attachurl_remote"] = $_W["setting"]["remote"]["ftp"]["url"] . "/";
				$_W["attachurl"] = $_W["attachurl_remote"];
			}
			else 
			{
				if( $_W["setting"]["remote"]["type"] == ATTACH_OSS ) 
				{
					$_W["attachurl_remote"] = $_W["setting"]["remote"]["alioss"]["url"] . "/";
					$_W["attachurl"] = $_W["attachurl_remote"];
				}
				else 
				{
					if( $_W["setting"]["remote"]["type"] == ATTACH_QINIU ) 
					{
						$_W["attachurl_remote"] = $_W["setting"]["remote"]["qiniu"]["url"] . "/";
						$_W["attachurl"] = $_W["attachurl_remote"];
					}
					else 
					{
						if( $_W["setting"]["remote"]["type"] == ATTACH_COS ) 
						{
							$_W["attachurl_remote"] = $_W["setting"]["remote"]["cos"]["url"] . "/";
							$_W["attachurl"] = $_W["attachurl_remote"];
						}
					}
				}
			}
		}
		static $com = NULL;
		if( !$com ) 
		{
			$com = com("qiniu");
		}
		$qiniu = m("common")->getSysset("qiniu");
		$data = $qiniu["user"];
		if( $com && 0 < $data["upload"] ) 
		{
			$qiniu_url = $com->save($url, NULL, $enforceQiniu);
			if( !empty($qiniu_url) && !is_error($qiniu_url) ) 
			{
				return $qiniu_url;
			}
		}
		else 
		{
			$data = '';
			$path = IA_ROOT . "/addons/imfox_eos/data/global";
			if( empty($data["upload"]) && is_file($path . "/qiniu.cache") ) 
			{
				$data_authcode = authcode(file_get_contents($path . "/qiniu.cache"), "DECODE", "global");
				$data = json_decode($data_authcode, true);
			}
			if( $com && 0 < $data["upload"] ) 
			{
				$qiniu_url = $com->save($url, $data, $enforceQiniu);
				if( !empty($qiniu_url) && !is_error($qiniu_url) ) 
				{
					return $qiniu_url;
				}
			}
		}
		$ext = strrchr($url, ".");
		if( $ext != ".jpeg" && $ext != ".gif" && $ext != ".jpg" && $ext != ".png" ) 
		{
			return $url;
		}
		if( !empty($_W["setting"]["remote"]["type"]) && !empty($url) && !(strexists($url, "http:") || strexists($url, "https:")) && is_file(ATTACHMENT_ROOT . $url) ) 
		{
			load()->func("file");
			$remotestatus = file_remote_upload($url, false);
			if( !is_error($remotestatus) ) 
			{
				$remoteurl = $_W["attachurl_remote"] . $url;
				return $remoteurl;
			}
		}
		if( strexists($url, $_W["siteroot"]) && !strexists($url, "/addons/") ) 
		{
			$urls = parse_url($url);
			$url = substr($urls["path"], strpos($urls["path"], "images"));
			if( file_exists(IA_ROOT . "/" . $_W["config"]["upload"]["attachdir"] . "/" . $url) ) 
			{
				return $url;
			}
		}
		return $url;
	}
}
function formatQueryParaMap($paraMap, $urlencode){
	$buff = "";
	ksort($paraMap);
	foreach ($paraMap as $k => $v){
		if (null != $v && "null" != $v && "sign" != $k) {
		    if($urlencode){
			   $v = urlencode($v);
			}
			$buff .= $k . "=" . $v . "&";
		}
	}
	$reqPar;
	if (strlen($buff) > 0) {
		$reqPar = substr($buff, 0, strlen($buff)-1);
	}
	return $reqPar;
}
function curl_post($url,$data){
    $curl = curl_init($url);
    curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 30);
    curl_setopt($curl, CURLOPT_TIMEOUT, 10);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($curl, CURLOPT_POST, 1);//发送一个常规的Post请求
	curl_setopt($curl, CURLOPT_POSTFIELDS, $data);//Post提交的数据包
    $rv = curl_exec($curl);//输出内容
    curl_close($curl);
    return $rv;
}
function httpcurl($url){
	$ch = curl_init($url);
	curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
	curl_setopt($ch, CURLOPT_TIMEOUT, 10);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
	curl_setopt($ch, CURLOPT_HEADER, false);
	$output = curl_exec($ch);//输出内容
	curl_close($ch);
	return $output;
}
function arrayToXml($arr){
    $xml = "<xml>";
    foreach ($arr as $key=>$val)
    {
    	 if (is_numeric($val))
    	 {
    	 	$xml.="<".$key.">".$val."</".$key.">"; 

    	 }
    	 else{
    	 	$xml.="<".$key."><![CDATA[".$val."]]></".$key.">";  
    	 } 
    }
    $xml.="</xml>";
    return $xml;
}
function orderquery($res,$wechat){
	$orderQueryUrl = 'https://api.mch.weixin.qq.com/pay/orderquery';
	$input = array();
	$input['appid'] = $res['appid'];
	$input['mch_id'] = $res['mch_id'];
	$input['out_trade_no'] = $res['out_trade_no'];
	$input['nonce_str'] = random(32);
	
	$unSignParaStr = formatQueryParaMap($input,false);
	$signStr = $unSignParaStr."&key=".$wechat['apikey'];
	$input['sign'] = strtoupper(md5($signStr));
	
	$orderQueryInfo = simplexml_load_string(curl_post($orderQueryUrl,arrayToXml($input)),'SimpleXMLElement', LIBXML_NOCDATA);//红包预下单返回信息
	$orderQueryInfo = json_decode(json_encode($orderQueryInfo),true);	
	return $orderQueryInfo;
}
function json_encode_ex($value){
	if(version_compare(PHP_VERSION,'5.4.0','<')){
		$str = json_encode($value);
		$str = preg_replace_callback(
			"#\\\u([0-9a-f]{4})#i",
			function($matchs){
				return iconv('UCS-2BE', 'UTF-8', pack('H4', $matchs[1]));
			},
			$str
		);
		return $str;
	}else{
		return json_encode($value, JSON_UNESCAPED_UNICODE);
	}
}
function getSignature($str, $key) {  
    $signature = "";  
    if (function_exists('hash_hmac')) {  
        $signature = base64_encode(hash_hmac("sha1", $str, $key, true));  
    } else {  
        $blocksize = 64;  
        $hashfunc = 'sha1';  
        if (strlen($key) > $blocksize) {  
            $key = pack('H*', $hashfunc($key));  
        }  
        $key = str_pad($key, $blocksize, chr(0x00));  
        $ipad = str_repeat(chr(0x36), $blocksize);  
        $opad = str_repeat(chr(0x5c), $blocksize);  
        $hmac = pack(  
                'H*', $hashfunc(  
                        ($key ^ $opad) . pack(  
                                'H*', $hashfunc(  
                                        ($key ^ $ipad) . $str  
                                )  
                        )  
                )  
        );  
        $signature = base64_encode($hmac);  
    }  
    return $signature;  
}
function is_utf8($str) 
{
	return preg_match('%^(?:' . "\r\n" . '            [\	\
\
\ -\~]              # ASCII' . "\r\n" . '            | [\?-\?][\?-\?]             # non-overlong 2-byte' . "\r\n" . '            | \?[\?-\?][\?-\?]         # excluding overlongs' . "\r\n" . '            | [\?-\?\?\?][\?-\?]{2}  # straight 3-byte' . "\r\n" . '            | \?[\?-\?][\?-\?]         # excluding surrogates' . "\r\n" . '            | \?[\?-\?][\?-\?]{2}      # planes 1-3' . "\r\n" . '            | [\?-\?][\?-\?]{3}          # planes 4-15' . "\r\n" . '            | \?[\?-\?][\?-\?]{2}      # plane 16' . "\r\n" . '            )*$%xs', $str);
}
function setSpacing($str, $length = 32) 
{
	$str_old = $str;
	$str = ((is_utf8($str) ? iconv('utf-8', 'gb2312', $str) : $str));
	$num = strlen($str);
	if ($length < $num) 
	{
		if ((32 < $num) && ($length == 32)) 
		{
			$temp = '';
			$count = ceil($num / $length);
			$i = 0;
			while ($i <= $count) 
			{
				$temp .= mb_substr($str_old, $i * $length, $length);
				++$i;
			}
			return $temp;
		}
		return mb_substr($str_old, 0, floor($length / 2), 'utf-8') . str_repeat(' ', $length % 2);
	}
	return $str_old . str_repeat(' ', $length - $num);
}
function wxappMessage($access_token,$touser,$template_id,$page,$form_id,$data,$emphasis_keyword){
	if(empty($access_token)){
		return error(1, 'access_token为空');
	}
	if(empty($touser)){
		return error(1, 'openid为空');
	}
	$postArr = array(
		'touser'			=>	$touser,
		'template_id'		=>	$template_id,
		'page'				=>	$page,
		'form_id'			=>	$form_id,
		'data'				=>	$data,
		'emphasis_keyword'	=>	$emphasis_keyword
	);
	if(empty($emphasis_keyword)){
		unset($postArr['emphasis_keyword']);
	}
	$postJson = json_encode_ex($postArr);
	$url = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=".$access_token;
	$response = ihttp_request($url, $postJson);
	$result = @json_decode($response['content'], true);
	return $result;
}
function eos_template($filename, $flag = TEMPLATE_DISPLAY) {
	global $_W;
	$name = 'imfox_eos';
	if (defined('IN_SYS')) {
		$template = 'default';
		$source = IA_ROOT . '/addons/' . $name . '/template/' . $template . '/' . $filename . '.html';
		$compile = IA_ROOT . '/data/tpl/web/' . $name . '/' . $template . '/' . $filename . '.tpl.php';
	}else{
		$template = 'default';
		$source = IA_ROOT . '/addons/' . $name . '/template/' . $template . '/' . $filename . '.html';
		$compile = IA_ROOT . '/data/tpl/web/' . $name . '/' . $template . '/' . $filename . '.tpl.php';
	}
	if(!is_file($source)) {
		echo "template source '{$filename}' is not exist!";
		return '';
	}
	if(DEVELOPMENT || !is_file($compile) || filemtime($source) > filemtime($compile)) {
		eos_template_compile($source, $compile);
	}
	return $compile;
}

function manage_url($params = array()){
	global $_W;
	$params['i'] = $_W['uniacid'];
	$params['do'] = "manage";
	$params['m'] = "deam_food";
	return wurl('site/entry', $params);
}
function get_last_day($year, $month) {
	return date('t', strtotime($year . '-' . $month . ' -1'));
}
function activity_get_coupon_colors() {
	$colors = array(
		'Color010' => '#55bd47',
		'Color020' => '#10ad61',
		'Color030' => '#35a4de',
		'Color040' => '#3d78da',
		'Color050' => '#9058cb',
		'Color060' => '#de9c33',
		'Color070' => '#ebac16',
		'Color080' => '#f9861f',
		'Color081' => '#f08500',
		'Color082' => '#a9d92d',
		'Color090' => '#e75735',
		'Color100' => '#d54036',
		'Color101' => '#cf3e36',
		'Color102' => '#5e6671',
	);
	return $colors;
}
function curl_post_ssl($url, $vars, $cert, $key,$second=30,$aHeader=array()){
	global $_W;
	$ch = curl_init();
	//超时时间
	curl_setopt($ch,CURLOPT_TIMEOUT,$second);
	curl_setopt($ch,CURLOPT_RETURNTRANSFER, 1);
	//这里设置代理，如果有的话
	//curl_setopt($ch,CURLOPT_PROXY, '10.206.30.98');
	//curl_setopt($ch,CURLOPT_PROXYPORT, 8080);
	curl_setopt($ch,CURLOPT_URL,$url);
	curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);
	curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,false);
	
	//以下两种方式需选择一种
	//第一种方法，cert 与 key 分别属于两个.pem文件
	curl_setopt($ch,CURLOPT_SSLCERT,$cert);
	curl_setopt($ch,CURLOPT_SSLKEY,$key);
 
	if( count($aHeader) >= 1 ){
		curl_setopt($ch, CURLOPT_HTTPHEADER, $aHeader);
	}
 
	curl_setopt($ch,CURLOPT_POST, 1);
	curl_setopt($ch,CURLOPT_POSTFIELDS,$vars);
	$data = curl_exec($ch);
	if($data){
		curl_close($ch);
		return $data;
	}
	else { 
		$error = curl_errno($ch);
		echo "call faild, errorCode:$error\n"; 
		curl_close($ch);
		return false;
	}
}
function imfox_msg($msg, $redirect = '', $type = '', $tips = false, $extend = array()){
	global $_W, $_GPC;

	if($redirect == 'refresh') {
		$redirect = $_W['script_name'] . '?' . $_SERVER['QUERY_STRING'];
	}
	if($redirect == 'referer') {
		$redirect = referer();
	}
		$redirect = safe_gpc_url($redirect);

	if($redirect == '') {
		$type = in_array($type, array('success', 'error', 'info', 'warning', 'ajax', 'sql')) ? $type : 'info';
	} else {
		$type = in_array($type, array('success', 'error', 'info', 'warning', 'ajax', 'sql')) ? $type : 'success';
	}
	if ($_W['isajax'] || !empty($_GET['isajax']) || $type == 'ajax') {
		if($type != 'ajax' && !empty($_GPC['target'])) {
			exit("");
		} else {
			$vars = array();
			$vars['message'] = $msg;
			$vars['redirect'] = $redirect;
			$vars['type'] = $type;
			exit(json_encode($vars));
		}
	}
	if (empty($msg) && !empty($redirect)) {
		header('Location: '.$redirect);
		exit;
	}
	$label = $type;
	if($type == 'error') {
		$label = 'danger';
	}
	if($type == 'ajax' || $type == 'sql') {
		$label = 'warning';
	}

	if (is_array($msg)){
		$message_cookie['title'] = 'MYSQL 错误';
		$message_cookie['msg'] = 'php echo cutstr(' . $msg['sql'] . ', 300, 1);';
	} else{
		$message_cookie['title'] = $caption;
		$message_cookie['msg'] = $msg;
	}
	$message_cookie['type'] = $label;
	$message_cookie['redirect'] = $redirect ? $redirect : referer();
	$message_cookie['msg'] = rawurlencode($message_cookie['msg']);
	$extend_button = array();
	if (!empty($extend) && is_array($extend)) {
		foreach ($extend as $button) {
			if (!empty($button['title']) && !empty($button['url'])) {
				$button['url'] = safe_gpc_url($button['url']);
				$button['title'] = rawurlencode($button['title']);
				$extend_button[] = $button;
			}
		}
	}
	$message_cookie['extend'] = !empty($extend_button) ? $extend_button : '';

	isetcookie('message', stripslashes(json_encode($message_cookie, JSON_UNESCAPED_UNICODE)));
	header('Location: ' . $message_cookie['redirect']);

	exit;
}
function num_to_rmb($num){
    $c1 = "零壹贰叁肆伍陆柒捌玖";
    $c2 = "分角元拾佰仟万拾佰仟亿";
    //精确到分后面就不要了，所以只留两个小数位
    $num = round($num, 2); 
    //将数字转化为整数
    $num = $num * 100;
    if (strlen($num) > 10) {
        return "金额太大，请检查";
    } 
    $i = 0;
    $c = "";
    while (1) {
        if ($i == 0) {
            //获取最后一位数字
            $n = substr($num, strlen($num)-1, 1);
        } else {
            $n = $num % 10;
        }
        //每次将最后一位数字转化为中文
        $p1 = substr($c1, 3 * $n, 3);
        $p2 = substr($c2, 3 * $i, 3);
        if ($n != '0' || ($n == '0' && ($p2 == '亿' || $p2 == '万' || $p2 == '元'))) {
            $c = $p1 . $p2 . $c;
        } else {
            $c = $p1 . $c;
        }
        $i = $i + 1;
        //去掉数字最后一位了
        $num = $num / 10;
        $num = (int)$num;
        //结束循环
        if ($num == 0) {
            break;
        } 
    }
    $j = 0;
    $slen = strlen($c);
    while ($j < $slen) {
        //utf8一个汉字相当3个字符
        $m = substr($c, $j, 6);
        //处理数字中很多0的情况,每次循环去掉一个汉字“零”
        if ($m == '零元' || $m == '零万' || $m == '零亿' || $m == '零零') {
            $left = substr($c, 0, $j);
            $right = substr($c, $j + 3);
            $c = $left . $right;
            $j = $j-3;
            $slen = $slen-3;
        } 
        $j = $j + 3;
    } 
    //这个是为了去掉类似23.0中最后一个“零”字
    if (substr($c, strlen($c)-3, 3) == '零') {
        $c = substr($c, 0, strlen($c)-3);
    }
    //将处理的汉字加上“整”
    if (empty($c)) {
        return "零元整";
    }else{
        return $c . "整";
    }
}
require IMFOX_ROOT. '/common/template.func.php';
?>